import rq from 'request-promise'
// import _ from 'lodash'
import iconv from 'iconv-lite'
import { writeFileSync } from 'fs'
import { resolve } from 'path'
const r = path => resolve(__dirname, path)
let provincePath = r('../../json/province.json')
let cityPath = r('../../json/city.json')

var province = require(provincePath)
var isclearTimer = false
const sign = 'c0159e56b92b0f7e191b2228d917afc9'
let idx = 0
let cityIdx = 0
let citys = []
const getApi = async () => {
  if (!province[idx].city) return
  
  if (province.length !== idx) {
    if (cityIdx === province[idx].city.length) {
      idx ++
    } else  {
      cityIdx ++
    }
  } else {
    if (cityIdx === province[idx].city.length) {
      return isclearTimer = true
    }
  }
  console.log(province[idx].name)
  let city = province[idx].name.replace(/市/,'')
  console.log(city)
  var url = `http://cp-tools.cn/search/hotPlace`
  console.log(url)
	const options = {
    url: url,
    json: true,
    qs: {
      city,
      sign
    }
	}
  var res = await rq(options)
  console.log(res)
  if (res.top)  citys.push(res.result)


  if (res.city) {
    province[idx].city = res.city
    writeFileSync(jsonPath, JSON.stringify(citys, null, 2), 'utf-8')
  }

	
}


const timer = setInterval(function() {
	getApi()
},3000)

const clearTime = setInterval(function() {
	if (isclearTimer) {
		clearInterval(timer)
	}
},1000)